import sqlite3
from sqlite3 import Error
import pathlib
from loger import log
root=pathlib.Path(__file__).parent
db=sqlite3.connect(str(root/"exam.db"))
cur = db.cursor()
classTimeDb=sqlite3.connect(root.parent/"timetable/classbook.db")
classTimeCur=classTimeDb.cursor()

def runsql(sql):
    try:
        r=cur.execute(sql)
    except Error as e:
        log.error(f"{e}")
        db.rollback()
        return (False,e)
    else:
        db.commit()
        return (True,r)

def runmanysql(sql,data):
    try:
        r=cur.executemany(sql,data)
    except Error as e:
        log.error(f"{e}")
        db.rollback()
        return (False,e)
    else:
        db.commit()
        return (True,r)

def setData(k,v):
    (s,_)=runsql(f"INSERT OR REPLACE INTO kv (k,v) VALUES ('{str(k)}','{str(v)}');")
    return s
def getData(k):
    (s,r)=runsql(f"select v from kv where k = '{str(k)}'")
    if(not s):
        return None
    r=r.fetchone()
    if(r is None):
        return None
    else:
        return r[0]
def delData(k):
    if(getData(k) is None):
        log.warning(f"{k}键不存在")
        return False
    else:
        (s,_)=runsql(f"DELETE FROM `kv` WHERE (`k`='{str(k)}');")
        return s